package net.zigin.nhi.waste.view.print;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gyf.immersionbar.ImmersionBar;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.adapter.IActivityUpData;
import net.zigin.nhi.waste.adapter.NoDataAdapter;
import net.zigin.nhi.waste.adapter.WasteLabelAdapter;
import net.zigin.nhi.waste.bean.WastePrintBean;
import net.zigin.nhi.waste.bean.WebWastePrintBean;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.utils.StringUtil;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import Printer.PrintHelper;
import io.paperdb.Paper;
import io.reactivex.Observable;

/**
 * 医废标签界面
 */
public class WasteLabelActivity extends AppCompatActivity {

    private RecyclerView mRv;
    private ImageView mImg;
    private Button mPrint;
    private WebView mWebView;

    private WasteLabelAdapter adapter;
    private NoDataAdapter noDataAdapter = new NoDataAdapter();
    private boolean isSelected = false;
    private List<WastePrintBean> beanList = new ArrayList<>();

    private PrintHelper printHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_waste_label);
        initView();

        printHelper = new PrintHelper();
        printHelper.Open(WasteLabelActivity.this);
    }

    private void initView() {
        ImmersionBar.with(this).init();
        mRv = findViewById(R.id.rv);
        mImg = findViewById(R.id.img);
        mPrint = findViewById(R.id.print);
        mWebView = findViewById(R.id.web_view);

        mRv.setLayoutManager(new LinearLayoutManager(this));
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onResume() {
        super.onResume();

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new PrintObject(), "connect");
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setDisplayZoomControls(false);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.loadUrl("file:///android_asset/wastelabel.html");

        getLabel();
        initData();
    }

    /**
     * 获取医废标签信息
     */
    private void getLabel() {
        beanList.clear();
        Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                .getCurrentCollectList(Paper.book().read(Constants.TOKEN));
        HttpRetrofitClient.execute(observable, new ApiCall<String>() {
            @Override
            protected void success(String result) {
                if (StringUtil.isNotEmpty(result)) {
                    Log.i("医废标签信息", result);
                    beanList = JSONArray.parseArray(result, WastePrintBean.class);
                    if (beanList != null && beanList.size() > 0) {
                        adapter = new WasteLabelAdapter(beanList, dd);
                        mRv.setAdapter(adapter);
                    } else {
                        mRv.setAdapter(noDataAdapter);
                    }
                } else {
                    mRv.setAdapter(noDataAdapter);
                }
            }
        });
    }

    private void initData() {
        mImg.setOnClickListener(v -> {
            if (isSelected) {
                isSelected = false;
                mImg.setImageResource(R.drawable.depot_in_unselected);

                for (WastePrintBean bean : beanList) {
                    bean.setSelect(false);
                }
            } else {
                isSelected = true;
                mImg.setImageResource(R.drawable.depot_in_selected);

                for (WastePrintBean bean : beanList) {
                    bean.setSelect(true);
                }
            }
            if (adapter != null) {
                adapter.notifyData(beanList);
            }

        });

        mPrint.setOnClickListener(v -> {
            mWebView.clearCache(true);
            Set<WastePrintBean> webList = new HashSet<>();   //给webView传参的list
            Set<WastePrintBean> newList = Paper.book().read(Constants.NEW_WASTE_LABEL_LIST);
            if (newList != null && newList.size() > 0) {
                for (WastePrintBean bean : newList) {
                    if (bean.isSelect()) {
                        //已选中的打印
                        webList.add(bean);
                    }
                }
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (WastePrintBean bean : webList) {
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //给webView传递数据
                        String json = JSONObject.toJSONString(bean);
                        Log.i("printObject", json);
                        String call = "javascript:getLabel('" + json + "')";
                        runOnUiThread(() -> {
                            mWebView.loadUrl(call);
                        });
                    }
                }
            }).start();

        });
    }

    /**
     * 子项取消选中时，全选按钮变更状态为未选中
     */
    private IActivityUpData dd = new IActivityUpData() {
        @Override
        public void upDataUi() {
            isSelected = false;
            mImg.setImageResource(R.drawable.depot_in_unselected);
        }
    };


    class PrintObject {
        @JavascriptInterface
        public void print(final int x, final int y, final int width, final int height) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Picture pic = mWebView.capturePicture();
                        int nw = pic.getWidth();
                        int nh = pic.getHeight();
                        Bitmap bitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_4444);
                        Canvas can = new Canvas(bitmap);
                        pic.draw(can);

                        int newWidth = nw;
                        int newHeight = nh;
                        if (nw > 400) {
                            float rate = 380 * 1.0f / nw * 1.0f;
                            newWidth = 380;
                            newHeight = (int) (nh * rate);
                        }
                        bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
                        Bitmap newBitmap = Bitmap.createBitmap(bitmap, x, y, width, height);
                        printHelper.PrintBitmap(newBitmap);

                        printHelper.printBlankLine(40);
                    } catch (Exception | Error e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        @JavascriptInterface
        public void doFeed() {
            printHelper.Step((byte) 0x5f);
        }
    }

}